|
|
|
|
|
|
|
Even though the variable I is initialized to the value 0, the loop executes before the Until condition is encountered. Executing this example causes the input box to be displayed repeatedly until the user enters 0. |
|
|
|
|
|
|
|
|
Another type of loop supported by Visual Basic is the For Each loop. The For Each loop is considered to be an enumeration loop because it is used for processing (or enumerating) each member of a set of objects. As you will see in Chapter 16, "Classes: Reusable Components," a group of objects can be stored in a collection. |
|
|
|
|
|
|
|
|
See ''Creating Classes That Contain Collections," p. 373 |
|
|
|
|
|
|
|
|
One example of a collection is the Printers collection, a built-in collection which represents each attached printer as an object. The following code uses a For Each loop to print the DeviceName property of all of the printers: |
|
|
|
|
|
|
|
|
Dim objPrinter As Printer
For Each objPrinter In Printers
Debug.Print objPrinter.DeviceName
Next objPrinter |
|
|
|
|
|
|
|
|
The object variable objPrinter acts similar to the counter variable in a For Next loop in that it contains the current item being processed. |
|
|
|
|
|
|
|
|
The For Each loop can also be used with an array, as in the following example: |
|
|
|
|
|
|
|
|
Dim nNumber As Variant
Dim MyArray As Variant
MyArray = Array(3, 6, 9, 9, 5, 2, 3, 9)
For Each nNumber In MyArray
If nNumber > 5 Then Debug.Print nNumber
Next nNumber |
|
|
|
|
|
|
|
|
The code first creates a variant array containing eight integers and then uses the enumeration loop to list each integer with a value greater than 5. |
|
|
|
|
|
|
|
|
As you write code and add objects to your VB programs, you should test them for bugs. A typical example of a bug occurs in a program that appears normal but does not work under all conditions. As a test, introduce an error now and debug it. Suppose that you want to use a While loop to print the numbers from 1 to 100 in the Immediate window. Start a new Standard EXE project, and enter the following code in the Form_Load event procedure: |
|
|
|
|
|